package root.electronclass.electronclass.mvp.rest;




import android.util.Log;

import com.blankj.utilcode.util.LogUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * Created by linlingrong on 2016-08-02.
 */
public class VoidInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    @Override
    public Response intercept( Chain chain) throws IOException {
        Request request = chain.request();

        // 打印请求body
        if (request.body() != null) {
            Buffer requestBuffer = new Buffer();
            request.body().writeTo(requestBuffer);
            Charset requestCharset = UTF8;
            MediaType requestContentType = request.body().contentType();
            if (requestContentType != null) {
                requestCharset = requestContentType.charset(UTF8);
            }
            String requestBodyString = requestBuffer.readString(requestCharset);
            LogUtils.json("http", "请求 URL: " + request.url() + " 请求body: " + requestBodyString);
        }

        Response response = chain.proceed(request);
        ResponseBody responseBody = response.body();

        // 打印响应body
        if (responseBody != null) {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            if (charset != null) {
                String bodyString = buffer.clone().readString(charset);
                LogUtils.json("http", "请求 URL: " + request.url() + " 返回: " + bodyString);
                if (bodyString.isEmpty() && response.body() != null) {
                    response.body().source().buffer().writeString("null", charset);
                }
            }
        }

        return response;
    }
}
